import React, { useState } from 'react';
import { Settings, Save, TestTube, AlertCircle, CheckCircle } from 'lucide-react';
import MenuToggle from '../components/MenuToggle';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import API_CONFIG, { updateBaseUrl } from '@/config/api';
import { http } from '@/utils/http';

const ApiConfig = ({ toggleSidebar }) => {
  const [config, setConfig] = useState({
    baseUrl: API_CONFIG.BASE_URL,
    timeout: API_CONFIG.TIMEOUT,
  });
  const [testResult, setTestResult] = useState(null);
  const [isTestingConnection, setIsTestingConnection] = useState(false);

  const handleSave = () => {
    // 更新全局API配置
    updateBaseUrl(config.baseUrl);
    API_CONFIG.TIMEOUT = config.timeout;
    
    console.log('API配置已保存:', config);
    alert('API配置已保存');
  };

  const testConnection = async () => {
    setIsTestingConnection(true);
    setTestResult(null);
    
    try {
      // 临时更新配置进行测试
      const originalBaseUrl = API_CONFIG.BASE_URL;
      updateBaseUrl(config.baseUrl);
      
      // 测试连接
      await http.get('/system/status');
      
      setTestResult({
        success: true,
        message: '连接成功',
        timestamp: new Date().toLocaleString()
      });
      
      // 恢复原配置
      updateBaseUrl(originalBaseUrl);
    } catch (error) {
      setTestResult({
        success: false,
        message: error.message || '连接失败',
        timestamp: new Date().toLocaleString()
      });
    } finally {
      setIsTestingConnection(false);
    }
  };

  return (
    <>
      {/* 头部工具栏 */}
      <div className="mt-3">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl flex items-center justify-center">
                  <Settings className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    API配置
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    管理后端接口地址和连接设置
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <Button 
                variant="outline" 
                onClick={testConnection}
                disabled={isTestingConnection}
              >
                {isTestingConnection ? (
                  <>
                    <div className="w-4 h-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin" />
                    测试中
                  </>
                ) : (
                  <>
                    <TestTube className="w-4 h-4 mr-2" />
                    测试连接
                  </>
                )}
              </Button>
              <Button onClick={handleSave} className="bg-primary hover:bg-primary-600">
                <Save className="w-4 h-4 mr-2" />
                保存配置
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        <div className="max-w-2xl mx-auto space-y-6">
          {/* API配置卡片 */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Settings className="w-5 h-5" />
                <span>接口配置</span>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label htmlFor="baseUrl">后端接口地址</Label>
                <Input
                  id="baseUrl"
                  value={config.baseUrl}
                  onChange={(e) => setConfig(prev => ({ ...prev, baseUrl: e.target.value }))}
                  placeholder="http://localhost:8080/api"
                />
                <p className="text-sm text-material-grey-600 mt-1">
                  所有API请求的基础地址，后续接口调用只需提供相对路径
                </p>
              </div>

              <div>
                <Label htmlFor="timeout">请求超时时间 (毫秒)</Label>
                <Input
                  id="timeout"
                  type="number"
                  value={config.timeout}
                  onChange={(e) => setConfig(prev => ({ ...prev, timeout: parseInt(e.target.value) || 10000 }))}
                  placeholder="10000"
                />
                <p className="text-sm text-material-grey-600 mt-1">
                  API请求的超时时间，超过此时间将自动取消请求
                </p>
              </div>
            </CardContent>
          </Card>

          {/* 连接测试结果 */}
          {testResult && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  {testResult.success ? (
                    <CheckCircle className="w-5 h-5 text-green-600" />
                  ) : (
                    <AlertCircle className="w-5 h-5 text-red-600" />
                  )}
                  <span>连接测试结果</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center justify-between">
                  <div>
                    <Badge className={testResult.success ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}>
                      {testResult.success ? '成功' : '失败'}
                    </Badge>
                    <p className="text-sm text-material-grey-600 mt-1">
                      {testResult.message}
                    </p>
                  </div>
                  <span className="text-xs text-material-grey-500">
                    {testResult.timestamp}
                  </span>
                </div>
              </CardContent>
            </Card>
          )}

          {/* 使用说明 */}
          <Card>
            <CardHeader>
              <CardTitle>使用说明</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div>
                <h4 className="font-medium text-material-grey-900 mb-2">配置说明</h4>
                <ul className="text-sm text-material-grey-600 space-y-1">
                  <li>• 后端接口地址：配置为 <code className="bg-material-grey-100 px-1 rounded">http://localhost:8080/api</code></li>
                  <li>• 后续所有API调用只需提供相对路径，如 <code className="bg-material-grey-100 px-1 rounded">/authority/login</code></li>
                  <li>• 系统会自动拼接完整的请求URL</li>
                </ul>
              </div>
              
              <div>
                <h4 className="font-medium text-material-grey-900 mb-2">API路径示例</h4>
                <div className="bg-material-grey-50 p-3 rounded-lg text-sm">
                  <div className="space-y-1">
                    <div><strong>用户登录：</strong> <code>/authority/login</code></div>
                    <div><strong>获取用户信息：</strong> <code>/authority/self</code></div>
                    <div><strong>文件上传：</strong> <code>/files/upload</code></div>
                    <div><strong>获取文件列表：</strong> <code>/files</code></div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </>
  );
};

export default ApiConfig;
